package com.beiben.work.process.service.impl;

import com.beiben.common.GlobalConstant;
import com.beiben.system.file.domain.File;
import com.beiben.system.file.mapper.FileMapper;
import com.beiben.system.file.service.IFileService;
import com.beiben.system.user.domain.BeiBenUser;
import com.beiben.system.user.service.IBeiBenUserService;
import com.beiben.work.process.domain.ExportProcessVo;
import com.beiben.work.process.domain.FileProcess;
import com.beiben.work.process.domain.FileProcessGroup;
import com.beiben.work.process.domain.FileProcessUser;
import com.beiben.work.process.mapper.FileProcessMapper;
import com.beiben.work.process.mapper.FileProcessUserMapper;
import com.beiben.work.process.service.IFileProcessService;
import com.beiben.work.process.service.IFileProcessUserService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysPost;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件任务管理Service业务层处理
 *
 * @author xgq
 * @date 2020-08-26
 */
@Service
public class FileProcessServiceImpl implements IFileProcessService {

    @Autowired
    private FileProcessMapper fileProcessMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private IFileProcessUserService fileProcessUserService;

    @Autowired
    private IFileService fileService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IBeiBenUserService beiBenUserService;

    /**
     * 查询文件任务管理
     *
     * @param workId 文件任务管理ID
     * @return 文件任务管理
     */
    @Override
    public FileProcess selectFileProcessById(Long workId) {
        return fileProcessMapper.selectFileProcessById(workId);
    }

    /**
     * 查询文件任务管理列表
     *
     * @param fileProcess 文件任务管理
     * @return 文件任务管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<FileProcess> selectFileProcessList(FileProcess fileProcess) throws ParseException {
        // TODO: 2020/10/26 默认查询 正在进行中的数据，全部状态运用数据字典添加，全部为-1，-1时查询全部
      if(null==fileProcess.getState()){
           fileProcess.setState(-2);
       }else  if(fileProcess.getState()==-1){
          fileProcess.setState(null);
      }
      List<FileProcess> fileProcesses = fileProcessMapper.selectFileProcessList(fileProcess);
        //判断任务是否超时
        this.checkProcessTimeOut(fileProcesses);
        return fileProcesses;
    }

    /**
     * 判断任务是否超时
     *
     * @param fileProcessList
     */
    private void checkProcessTimeOut(List<FileProcess> fileProcessList) throws ParseException {
        // 超时总任务 workId 集合
        List<Long> timeOutFIleProcessIds = new ArrayList<>();
        // 循环总任务
        for (FileProcess fileProcess : fileProcessList) {
            // 判断总任务是否完成
            if ("5".equals(fileProcess.getState())) {
                //任务完成 不做超时处理
                break;
            }
            // 判断总任务是否超时
            if ("Y".equals(fileProcess.getIsTimeOut())) {
                // 任务超时 不重新做超时验证
                break;
            }
            // 判断完成时间 是否 在今天之前 若在今天之前则任务超时 做分任务超时 及总任务超时
            if (fileProcess.getFinishTime().before(DateUtils.parseDate(DateUtils.getDate(), DateUtils.YYYY_MM_DD))) {
                timeOutFIleProcessIds.add(fileProcess.getWorkId());
            }
        }
        if (timeOutFIleProcessIds.size() > 0) {
            // 修改总任务超时状态
            fileProcessMapper.updateFileProcessTimeOutById(timeOutFIleProcessIds);
        }
    }

    /**
     * 新增文件任务管理
     *
     * @param fileProcess 文件任务管理
     * @return 结果
     */
    @Override
    public int insertFileProcess(FileProcess fileProcess) {
        fileProcess.setCreateTime(DateUtils.getNowDate());
        fileProcess.setCreateBy(SecurityUtils.getUsername());
        fileProcess.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        int result = fileProcessMapper.insertFileProcess(fileProcess);
        return result;
    }
    /**
     * 修改文件任务管理
     *
     * @param fileProcess 文件任务管理
     * @return 结果
     */
    @Override
    public int updateFileProcess(FileProcess fileProcess) {
        fileProcess.setUpdateTime(DateUtils.getNowDate());
        fileProcess.setUpdateBy(SecurityUtils.getUsername());
        // TODO: 2020/12/16  修改工作内容
        updateWorkItem(fileProcess);
        return fileProcessMapper.updateFileProcess(fileProcess);
    }

    /*
    * 修改分派任务工作
    * */
    public void updateWorkItem(FileProcess fileProcess){
        FileProcessUser fileProcessUser = new FileProcessUser();
        fileProcessUser.setWorkId(fileProcess.getWorkId());
        fileProcessUser.setIsSubmitFile(fileProcess.getIsSubmitFile());
        fileProcessUser.setSubmitName(fileProcess.getSubmitName());
        fileProcessUser.setWorkContent(fileProcess.getWorkContent());
        fileProcessUser.setDeptId(fileProcess.getDeptId());
        fileProcessUser.setCheckUserId(fileProcess.getUserId());
        fileProcessUserService.updateFileProcessUserByWorkId(fileProcessUser);
    }
    /**
     * 批量删除文件任务管理
     *
     * @param workIds 需要删除的文件任务管理ID
     * @return 结果
     */
    @Override
    public int deleteFileProcessByIds(Long[] workIds) {
        fileProcessUserService.deleteFileProcessByWorkIds(workIds);
        fileService.deleteFileByTableIds(GlobalConstant.WORK_FILE_PROCESS,workIds);
        return fileProcessMapper.deleteFileProcessByIds(workIds);
    }

    /**
     * 删除文件任务管理信息
     *
     * @param workId 文件任务管理ID
     * @return 结果
     */
    @Override
    public int deleteFileProcessById(Long workId) {
        fileProcessUserService.deleteFileProcessByWorkId(workId);
        return fileProcessMapper.deleteFileProcessById(workId);
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<ExportProcessVo> handleExport(ExportProcessVo exportProcessVo) {
        return fileProcessMapper.handleExport(exportProcessVo);
    }

    @Override
    public List<File> selectFiles(Long workId) {
        File file = new File();
        file.setTableId(workId);
        file.setTableName( GlobalConstant.WORK_FILE_PROCESS);
        return fileMapper.selectFileList(file);
    }
    /**
     * 按workId,deptId获取文件列表
     *
     * @param workId
     * @return
     */
    @Override
    public List<BeiBenUser> getUserInfo(Long workId) {
        return fileProcessMapper.getUserInfo(workId);
    }

    @Override
    public List<BeiBenUser> getUserInfoEdit(Long itemId,Long workId) {
        return fileProcessMapper.getUserInfoEdit(itemId,workId);
    }


    /**
     * 当前用户提醒带完成任务
     *
     * @param
     * @return
     */
    @Override
    public AjaxResult remindMe() {
        boolean isMe = false;
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        List<SysPost> list = beiBenUserService.selectUserPostByUserId(user.getUserId());
        for(SysPost post : list){
            if("dir".equals(post.getPostCode())){
                isMe = true;
            }
        }
        if(isMe){
            List<ExportProcessVo> listProcess = fileProcessMapper.selectFileProcessByUserId(user.getUserId());
            return AjaxResult.success(listProcess);
        }else{
            return AjaxResult.success();
        }
    }
}
